package foo.bar.wiki.web.action.resource;

import foo.bar.wiki.web.action.BaseActionBean;
import foo.bar.wiki.web.extension.ResourceTypeConverter;
import foo.bar.wiki.domain.Resource;
import foo.bar.wiki.services.WikiService;
import foo.bar.wiki.utils.IOUtils;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.integration.spring.SpringBean;

import java.io.IOException;
import java.sql.Blob;

/**
 * @author tmjee
 * @version $Date$ $Id$
 */
public class EditResourceActionBean extends BaseActionBean {

    public static final String VIEW = "/resource/editResource.jsp";

    private WikiService wikiService;


    @Validate(required = true, on = {"save"})
    private FileBean file;

    @Validate(converter = ResourceTypeConverter.class)
    private Resource resource;

    @DefaultHandler
    public Resolution view() {
        return new ForwardResolution(generateThemePath(VIEW));
    }

    public Resolution save() throws IOException {
        resource.setMimeType(file.getContentType());
        resource.setContent(IOUtils.toBytes(file.getInputStream()));
        wikiService.updateResource(resource);
        getContext().getMessages().add(new SimpleMessage("Resource ["+resource.getName()+"] updated successfully"));
        return new RedirectResolution(EditResourceActionBean.class, "view")
                .addParameter("resource", resource.getId());
    }



    @SpringBean("wikiService")
    public void setWikiService(WikiService wikiService) {
        this.wikiService = wikiService;
    }

    public Resource getResource() {
        return resource;
    }

    public void setResource(Resource resource) {
        this.resource = resource;
    }

    public FileBean getFile() {
        return file;
    }

    public void setFile(FileBean file) {
        this.file = file;
    }
}
